package cn.itsource.service.impl;

import cn.hutool.http.HttpUtil;
import cn.itsource.domain.Login;
import cn.itsource.dto.AccessTokenDto;
import cn.itsource.dto.LoginMealDto;
import cn.itsource.mapper.LoginMapper;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author Jason
 * @since 2022-08-29
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Autowired
    private LoginMapper loginMapper;
    @Value("${system.app-id}")
    private String appId;

    @Value("${system.app-secret}")
    private String appSecret;
    @Override
    public JSONResult saveLoginMeal(LoginMealDto dto) {
        loginMapper.saveLoginMeal(dto);
        return JSONResult.success();
    }
    //获取token
    @Override
    public JSONResult login(Login login) {
        /**
         * 1、入参校验
         * 2、判断用户名是否存在
         * 3、发请求获取token
         *  请求地址：http://localhost:1050/oauth/token?client_id=admin&client_secret=123456&grant_type=password&redirect_uri=http://www.baidu.com&username=987423749832489&password=123456
         * 4、封装信息返回前端
         */
        String url = "http://localhost:1050/oauth/token?client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";
        url = String.format(url, appId, appSecret, login.getUsername(), login.getPassword());
        //发请求获取token
        String result = HttpUtil.post(url, "");

        //将返回值封装成dto对象
        AccessTokenDto accessTokenDto = JSONObject.parseObject(result, AccessTokenDto.class);

        return JSONResult.success(accessTokenDto);
    }
}